package com.haruhi.botopq.event;

import com.alibaba.fastjson.JSONObject;
import com.haruhi.botopq.event.vo.SentMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Slf4j
@Component
public class ServerEndpoint extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
        log.info("客户端连接成功,sessionId:{}", session.getId());
        new Thread(()->{
            try {
                Thread.sleep(2000);
                SentMessage sentMessage = new SentMessage();
                SentMessage.CgiRequest cgiRequest = new SentMessage.CgiRequest();
                //  MessageSvc.PbSendMsg
                sentMessage.setCgiCmd("GetFriendLists");
                cgiRequest.setContent("nihao ");
                cgiRequest.setToType(2);
                cgiRequest.setToUin(681771058L);
                sentMessage.setCgiRequest(cgiRequest);
                sentMessage.setReqId(1312313);
                sentMessage.setBotUin("2995339277");
                System.out.println(JSONObject.toJSONString(sentMessage));
                session.sendMessage(new TextMessage(JSONObject.toJSONString(sentMessage)));
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }
        }).start();
      
    }

    @Override
    public void handleTextMessage(final WebSocketSession session, final TextMessage message) throws Exception {
        log.info("收到opq消息 {}",message.getPayload());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("连接异常,sessionId:{}",session.getId(),exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.info("连接断开,sessionId:{},{}",session.getId(),closeStatus.toString());
    }
    
}
